package tool

import (
	"github.com/dgrijalva/jwt-go"
	"newapp/model"
	"time"
)

type MyClaims struct {
	UserName string
	UserId uint
	jwt.StandardClaims
}

var jwtKey = []byte("gengchengcai")

func ReleaseToken(user model.User)(string, error){

	claims := &MyClaims{
		UserName: user.UserName,
		UserId: user.ID,
		StandardClaims:jwt.StandardClaims{
			ExpiresAt: time.Now().Add(7*time.Minute).Unix(),
			Issuer: "gengchengcai",
			IssuedAt: time.Now().Unix(),
		},

	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenstring, err := token.SignedString(jwtKey)
	if err!=nil{
		return "", err
	}

	return tokenstring,nil
}

func ParseToken(tokenString string) (*jwt.Token,*MyClaims,error ) {
	claims := &MyClaims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})
	return token, claims, err
}